package com.shanghaionstar.carmanage;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.framework.utils.RxSubscriptions;
import com.onstar.cn.mag.enumtype.PackageType;
import com.onstar.cn.map.util.ToastUtil;
import com.onstar.cn.payme.payutil.wxpay.WXPayUtil;
import com.onstar.cn.payme.response.CreateOrderResponseType;
import com.onstar.cn.smart.entity.PayChannelResponseEntity;
import com.shanghaionstar.R;
import com.shanghaionstar.carmanage.iview.ICarFlowOrderInfoViewImpl;
import com.shanghaionstar.carmanage.iview.IPayChannelView;
import com.shanghaionstar.carmanage.pay.alipay.AliPayUtil;
import com.shanghaionstar.carmanage.pay.alipay.AliWebPayRepEntity;
import com.shanghaionstar.carmanage.presenter.FlowOrderInfoPresenter;
import com.shanghaionstar.carmanage.presenter.PayChannelPresenter;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.enumtype.PayTypeEnum;
import com.shanghaionstar.enumtype.PayTypeLayout;
import com.shanghaionstar.report.bean.ReportReqParam;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.ErrorCodeUtil;
import com.shanghaionstar.wxapi.WXPayEntryActivity;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;

import java.util.List;

import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;


/**
 * 关于支付：
 * 支付方式有三种：微信，支付宝，支付宝web支付，主要逻辑：
 * <p/>
 * 微信：  { 根据套餐订单信息拼接支付信息，支付成功后调用接口查询服务端订单支付状况，支付成功——提示、并关闭购买套餐页面、跳转到支付记录列表页面。}
 * <p/>
 * 支付宝：{ 同微信 }
 * <p/>
 * 支付宝web支付：{ 需要根据订单信息请求订单支付宝webUrl以及支付成功回调路径callbackurl,
 * 跳转至AliWebPayActivity显示支付路径，在AliWebPayActivity中支付成功，
 * 则抛出AliPayUtil.ALIWEB_PAY_SUCCESS，调用接口查询服务端订单支付状况，
 * 支付成功——提示、并关闭购买套餐页面、跳转到支付记录列表页面。}
 *
 * @author Yonglang Hong
 * @ClassName: OrderPayActivity
 * @Description: 支付订单明细
 * @date 2015年9月9日 下午2:38:58
 */
@ContentView(R.layout.car_manage_activity_flow_pay)
public class OrderPayActivity extends BaseActivity implements IPayChannelView {

    public static final int PAY_SUCCESS = 11111;

    public static final String PACKAGE_ID = "packageId";
    public static final String PACKAGE_TYPE = "packageType";
    public static final String PACKAGE_PRICE = "packagePrice";
    public static final String PACKAGE_NAME = "packageName";

    /**********
     * 叉叉关闭按钮
     ******/
    @FindViewById
    private ImageView img_close;
    /****
     * 套餐价格、支付方式显示
     *****/
    @FindViewById
    private TextView tv_price, tv_packagePrice, tv_payWay;
    /*******
     * 加载套餐价格进度条
     ******/
    @FindViewById
    private ProgressBar pbar_packagePrice;
    /***********
     * 立即支付按钮
     **********/
    @FindViewById
    private View btn_payOrder;
    /**
     * 切换支付方式视图
     */
    private PayTypeLayout payTypeLayout;

    private ProgressDialog mDialog;
    /***********
     * 默认微信支付
     **********/
    PayTypeEnum payTypeEnum = PayTypeEnum.WECHATAPP;
    /*************
     * 页面参数
     ************/
    PackageType packageType;
    /**********
     * 订单信息
     **********/
    private CreateOrderResponseType orderInfo;
    /**********
     * 微信支付
     **********/
    private WXPayUtil wxPayUtil;
    /*********
     * 支付宝支付
     *********/
    private AliPayUtil aliPayUtil;

    private FlowOrderInfoPresenter orderInfoPresenter;

    //支付渠道相关
    private static final String DEFAULT_PAY_CHANNEL_KEY = "default_pay_channel";
    private PayChannelPresenter presenter;
    List<PayChannelResponseEntity.ChannelsBean> paychannels;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String packagePrice = bundle.getString(PACKAGE_PRICE);
            tv_packagePrice.setText(TextUtils.isEmpty(packagePrice) ? "" : ("￥" + CommonUtil.returnFormatString(packagePrice)));
        }
//        init();

        //请求服务器渠道数据
        getPayChannelData();
    }

    private void init() {
        loadOrderInfo();
    }

    /**
     * 异步加载订单信息
     */
    private void loadOrderInfo() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String packageId = bundle.getString(PACKAGE_ID).toString();
            String packageName = bundle.getString(PACKAGE_NAME, getString(R.string.taocan_price)).toString();
            packageType = (PackageType) getIntent().getExtras().getSerializable(PACKAGE_TYPE);

            setPackageName(packageName);
            //设置显示进度条，支付按钮不可点击
            setUpViewsOnPreLoad();
            //异步请求订单信息
            getOrderInfoPresenter().loadFlowOrderInfo(packageType, packageId);
        }
    }

    private void setPackageName(String name) {
        tv_price.setText(name);
    }

    @Override
    public BasePresenter getPresenter() {
        return null;
    }

    public FlowOrderInfoPresenter getOrderInfoPresenter() {
        if (orderInfoPresenter == null) {
            orderInfoPresenter = new FlowOrderInfoPresenter(getScheduler(), this);
            attachLogicalView();
        }
        return orderInfoPresenter;
    }

    /**
     * 绑定业务逻辑
     */
    private void attachLogicalView() {
        orderInfoPresenter.setOrderInfoView(new ICarFlowOrderInfoViewImpl() {
            @Override
            public void showErrOnLoadOrder(Throwable throwable) {
                dismisLoading();
                OrderPayActivity.this.showErrOnLoadOrder(throwable);
            }

            @Override
            public void showOrderInfo(CreateOrderResponseType orderInfo) {
                OrderPayActivity.this.showOrderInfo(orderInfo);
                pay();
            }

            @Override
            public void showErrOnQueryOrderStatus(Throwable throwable) {
                OrderPayActivity.this.showErrOnQueryOrderStatus(throwable);
            }

            @Override
            public void doByOrderPayStatus(String orderStatus) {
                OrderPayActivity.this.doByOrderPayStatus(orderStatus);
            }

            @Override
            public void onAliWebPaySuccess(AliWebPayRepEntity webPayRepEntity) {
                OrderPayActivity.this.onAliWebPaySuccess(webPayRepEntity);
            }

            @Override
            public void onAliWebPayFail(Throwable throwable) {
                OrderPayActivity.this.onAliWebPayFail(throwable);
            }

            @Override
            public void genSignReq(PayReq req, String payType) {
                sendPay(req, payType);
            }
        });
    }

    private void sendPay(PayReq req, String payType) {
        dismisLoading();
        if (payType.equalsIgnoreCase(PayTypeEnum.WECHATAPP.getStringValue())) {
            wxPayUtil.sendPay(req);
        } else {
            String sign = req.sign;
            aliPayUtil.pay(sign);
        }
    }

    /**
     * 请求支付宝webpay信息成功
     *
     * @param webPayRepEntity
     */
    public void onAliWebPaySuccess(AliWebPayRepEntity webPayRepEntity) {
        dismisLoading();
        Intent intent = new Intent(this, AliWebPayActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(AliWebPayActivity.ALIWEB_PAY, webPayRepEntity);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 请求支付宝webpay信息成失败
     */
    public void onAliWebPayFail(Throwable throwable) {
        dismisLoading();
        ErrorCodeUtil.ShowErrorSompMsg(
                this
                , BusinessUtil.getErrorInfoByException(this, (Exception) throwable)
                , new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
    }

    /**
     * 显示套餐订单信息
     *
     * @param orderInfo
     */
    private void showOrderInfo(CreateOrderResponseType orderInfo) {
        this.orderInfo = orderInfo;
        pbar_packagePrice.setVisibility(View.GONE);
        btn_payOrder.setEnabled(true);
        if (orderInfo != null && orderInfo.getPackageInfo() != null) {
            tv_packagePrice.setText("￥" + CommonUtil.returnFormatString(orderInfo.getPackageInfo().getActualPrice()));
        } else {
            AlertDialogUtil.showAlertDialog(this, R.string.dialog_warning, R.string.SOMP_903);
        }
    }

    /**
     * 处理加载套餐订单信息出错情况
     *
     * @param throwable
     */
    private void showErrOnLoadOrder(Throwable throwable) {
        if (throwable instanceof HttpException)
            AlertDialogUtil.showDialogByExceptionCode(this, (HttpException) throwable, new AlertDialogUtil.AlertDialogEventProxy() {
                @Override
                public void onPositiveClickListener(DialogInterface dialog) {
                    finish();
                }

                @Override
                public void onCancelListener(DialogInterface dialog) {
                    finish();
                }
            });
//        finish();
    }

    /**
     * 根据订单支付状态做一些事情
     */
    private void doByOrderPayStatus(String orderStatus) {
        log.d("orderStatus == " + orderStatus);
        dismisLoading();
        if (!CommonUtil.isNull(orderStatus) && ("3".equals(orderStatus) || "2".equals(orderStatus))) {
            AlertDialogUtil.showAlertDialog(this, R.string.dialog_warning,
                    R.string.alipay_9000, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //支付成功：关闭套餐选择页面和当前支付页面，并跳转订单记录页面
                            RxBus.getDefault().post(PAY_SUCCESS, PAY_SUCCESS);
                            Intent intent = new Intent(OrderPayActivity.this, OrderRecordActivity.class);
                            intent.putExtras(getIntent().getExtras());
                            startActivity(intent);
                            finish();
                        }
                    });
        } else {
            AlertDialogUtil.showAlertDialog(this, R.string.dialog_warning,
                    R.string.SB027_MSG009, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //支付异常
                            Intent intent = new Intent(OrderPayActivity.this,
                                    OrderRecordActivity.class);
                            intent.putExtras(getIntent().getExtras());
                            startActivity(intent);
                            finish();
                        }
                    });
        }
    }

    /**
     * 处理查询订单状态出错情况
     *
     * @param throwable
     */
    private void showErrOnQueryOrderStatus(Throwable throwable) {
        dismisLoading();
        if (throwable instanceof HttpException)
            AlertDialogUtil.showDialogByExceptionCode(this, (HttpException) throwable);
    }

    /**
     * 请求之前,该隐藏的隐藏，不可点击的取消点击
     */
    private void setUpViewsOnPreLoad() {
//        pbar_packagePrice.setVisibility(View.GONE);
        btn_payOrder.setEnabled(false);
    }

    @OnClick({R.id.img_close, R.id.rl_switchPayWay, R.id.btn_payOrder})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_close:
                if (PackageType.CORE == packageType) {
                    BusinessUtil.sendReportByClickType(this, FunctionNameFindId.OnstarPackage_purahcecancel.getStringValue());
                } else if (PackageType.DATA == packageType) {
                    BusinessUtil.sendReportByClickType(this, FunctionNameFindId.F4Gpacakge_purchasecancel.getStringValue());
                }
                finish();
                break;
            case R.id.rl_switchPayWay:
                showSwitchTypeDialog();
                break;
            case R.id.btn_payOrder:
                if (PackageType.CORE == packageType) {
                    BusinessUtil.sendReportByClickType(this, FunctionNameFindId.OnstarPackage_purchasecomfirm.getStringValue());
                } else if (PackageType.DATA == packageType) {
                    BusinessUtil.sendReportByClickType(this, FunctionNameFindId.F4Gpacakge_purchasecomfirm.getStringValue());
                }
                pbar_packagePrice.setVisibility(View.VISIBLE);
                init();
                break;
        }
    }


    private void pay() {
        switch (payTypeEnum) {
            case ALIPAYAPP:
                AliPay();
                break;
            case ALIPAYWEB:
                webPay();
                break;
            case WECHATAPP:
                WXPay();
                break;
        }
    }

    private void webPay() {
        if (aliPayUtil == null) {
            aliPayUtil = new AliPayUtil(this);
            //支付宝网页支付（其实是由AliWebPayProxy代理执行aliwebpay请求）
            aliPayUtil.setAliWebPayProxy(new AliPayUtil.AliWebPayProxy() {
                @Override
                public void pay(CreateOrderResponseType orderInfo) {
                    //aliwebpay实际支付请求
                    showLoading();
                    getOrderInfoPresenter().payByAliWeb(orderInfo);
                    setAliWebPayResultCallback();
                }
            });
            aliPayUtil.setAliPayCheckListener(new AliPayUtil.AliPayCheckListener() {
                @Override
                public void onCheckFail() {
                    BusinessUtil.sendReportByRequestParams(OrderPayActivity.this, getFunctionIdByPackageType(packageType), ReportReqParam.getPayReqParam(getFunctionIdByPackageType(packageType), false, "check fail"));

                }
            });
            //设置支付宝支付结果监听
//                setAliAPPPayResultCallback();
        }
        aliPayUtil.pay(payTypeEnum, orderInfo);
    }

    /********************** 微信支付分割线: look down*********************/
    /**
     * 关于微信支付注意点：
     * 微信支付成功后，点击home键再回到当前页面，会导致支付结果丢失，无法继续后续操作，
     * 所以需要添加一个isWXPayReqSended标志，如果微信支付请求已发出，则记为true，当
     * 出现上述异常情况再回到支付页面时，根据isWXPayReqSended == true来请求订单支付
     * 信息，结合正常支付流程（可以监听支付结果），将isWXPayReqSended作为同步块，防止两次
     * 请求订单支付信息
     */

    //微信支付请求是否发出
    private Boolean isWXPayReqSended = false;

    private void WXPay() {
        if (wxPayUtil == null) {
            wxPayUtil = new WXPayUtil(this);
            wxPayUtil.setPayListener(new WXPayUtil.wxpayListener() {
                @Override
                public void isWXInstalled(boolean isInstall) {
                    isWXPayReqSended = false;
                    dismisLoading();
                    AlertDialogUtil.showAlertDialog(
                            OrderPayActivity.this,
                            R.string.dialog_warning,
                            isInstall ? R.string.wechat_version_error : R.string.wechat_no_installed);
                }

                @Override
                public void onPayFailed() {
                    log.d("onPayFailed...");
                    BusinessUtil.sendReportByRequestParams(OrderPayActivity.this, getFunctionIdByPackageType(packageType), ReportReqParam.getPayReqParam(getFunctionIdByPackageType(packageType), false, getString(R.string.wechat_request_error)));
                    isWXPayReqSended = false;
                    dismisLoading();
                    AlertDialogUtil.showAlertDialog(
                            OrderPayActivity.this,
                            R.string.dialog_warning,
                            R.string.wechat_request_error);
                }

                @Override
                public void onPayErr(Exception e) {
                    BusinessUtil.sendReportByRequestParams(OrderPayActivity.this, getFunctionIdByPackageType(packageType), ReportReqParam.getPayReqParam(getFunctionIdByPackageType(packageType), false, e.getMessage()));
                    log.d("onPayErr..." + e.getMessage());
                    isWXPayReqSended = false;
                    dismisLoading();
                    ErrorCodeUtil.ShowErrorSompMsg(
                            OrderPayActivity.this,
                            BusinessUtil.getErrorInfoByException(OrderPayActivity.this, e));
                }

                @Override
                public void sendPayReq(Boolean isSend) {
                    log.d("sendPayReq" + isSend);
                    OrderPayActivity.this.isWXPayReqSended = isSend;
                }
            });
            setWXPayResultCallback();
        }
        showLoading();
        getOrderInfoPresenter().genSignForOrder(orderInfo, payTypeEnum.getStringValue());
//        showLoading();
//        wxPayUtil.pay(this, orderInfo);
    }

    private String getFunctionIdByPackageType(PackageType packageType) {
        if (packageType == PackageType.CORE) {
            return FunctionNameFindId.OnstarPackage_BuyServicePackage.getStringValue();
        } else if (packageType == PackageType.DATA) {
            return FunctionNameFindId.BuyMoreDataPackage_4G.getStringValue();
        }
        return "";
    }

    @Override
    protected void onResume() {
        super.onResume();
        /**
         *  避免支付完成后按home键导致无法接收到支付结果
         *  （不点击微信支付完成按钮不会回调WXPayEntryActivity中的onResp方法）
         */
        log.d("isWXPayReqSended" + isWXPayReqSended);
        synchronized (isWXPayReqSended) { //采用同步块，防止支付成功后多次查询订单状态，见方法：setWXPayResultCallback()
            if (isWXPayReqSended) {
                dismisLoading();
                isWXPayReqSended = false;
                if (WXPayUtil.WX_RESP_CODE == BaseResp.ErrCode.ERR_OK)
                    queryOrderStatus();
            }
        }
    }

    /**
     * 设置微信支付结果监听
     */
    private void setWXPayResultCallback() {
        mWxPayRx = RxBus.getDefault().toObserverable(WXPayEntryActivity.WX_PAY_RESULT_CODE, BaseResp.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BaseResp>() {
                    @Override
                    public void call(BaseResp resp) {
                        log.d("支付回调.....setWXPayResultCallback");
                        synchronized (isWXPayReqSended) {
                            if (isWXPayReqSended)
                                isWXPayReqSended = false;
                            dismisLoading();
                            if (resp.errCode == BaseResp.ErrCode.ERR_OK) {
                                //保存默认支付名称
                                PreferencesUtls.getInstance(OrderPayActivity.this).putString(DEFAULT_PAY_CHANNEL_KEY, tv_payWay.getText().toString());
                                log.d("微信支付成功.....开始查询订单状态");
                                BusinessUtil.sendReportByRequestParams(OrderPayActivity.this, getFunctionIdByPackageType(packageType), ReportReqParam.getPayReqParam(getFunctionIdByPackageType(packageType), true));
                                queryOrderStatus();
                            } else {
                                if (!TextUtils.isEmpty(resp.errStr))
                                    ToastUtil.show(OrderPayActivity.this, resp.errStr);
                            }
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        dismisLoading();
                        BusinessUtil.sendReportByRequestParams(OrderPayActivity.this, getFunctionIdByPackageType(packageType), ReportReqParam.getPayReqParam(getFunctionIdByPackageType(packageType), false, throwable.getMessage()));
                        ErrorCodeUtil.ShowErrorSompMsg(
                                OrderPayActivity.this,
                                BusinessUtil.getErrorInfoByException(OrderPayActivity.this, (Exception) throwable));
                    }
                });
        RxSubscriptions.add(mWxPayRx);
    }
    /*************************** 微信支付分割线：look up************************/

    /************************* 支付宝支付分割线：look down***********************/
    /**
     * 关于支付宝支付：
     * NOTE:
     * 支付宝支付注意H5PayActivity需要在Mainifest文件中注册；
     * 由于支付宝WEB支付与支付宝是封装在同一个类下，
     * 为了功能接口统一原则（也即支付宝/web支付只需要调用一个方法即可），
     * 需要手动设置web支付代理：AliWebPayProxy，在代理方法块中实现web支付
     */
    private void AliPay() {
        if (aliPayUtil == null) {
            aliPayUtil = new AliPayUtil(this);
            //支付宝网页支付（其实是由AliWebPayProxy代理执行aliwebpay请求）

            aliPayUtil.setAliPayCheckListener(new AliPayUtil.AliPayCheckListener() {
                @Override
                public void onCheckFail() {
                    BusinessUtil.sendReportByRequestParams(OrderPayActivity.this, getFunctionIdByPackageType(packageType), ReportReqParam.getPayReqParam(getFunctionIdByPackageType(packageType), false, "check fail"));

                }
            });
            //设置支付宝支付结果监听
            setAliAPPPayResultCallback();
        }
        showLoading();
        aliPayUtil.setContent(payTypeEnum, orderInfo);
        getOrderInfoPresenter().genSignForOrder(orderInfo, payTypeEnum.getStringValue());
//        aliPayUtil.pay(payTypeEnum, orderInfo);
    }

    private Subscription mAliPayRx, mAliWebPayRx, mWxPayRx;

    /**
     * /**
     * 监听支付宝APP支付结果
     */
    private void setAliAPPPayResultCallback() {
        mAliPayRx = RxBus.getDefault().toObserverable(AliPayUtil.ALIAPP_PAY_SUCCESS, String.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        log.d("setAliPayResultCallback == " + s);
                        if ("9000".equals(s)) {
                            //保存默认支付名称
                            PreferencesUtls.getInstance(OrderPayActivity.this).putString(DEFAULT_PAY_CHANNEL_KEY, tv_payWay.getText().toString());
                            BusinessUtil.sendReportByRequestParams(OrderPayActivity.this, getFunctionIdByPackageType(packageType), ReportReqParam.getPayReqParam(getFunctionIdByPackageType(packageType), true));
                            queryOrderStatus();
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        dismisLoading();
                        BusinessUtil.sendReportByRequestParams(OrderPayActivity.this, getFunctionIdByPackageType(packageType), ReportReqParam.getPayReqParam(getFunctionIdByPackageType(packageType), false, throwable.getMessage()));
                        ErrorCodeUtil.ShowErrorSompMsg(
                                OrderPayActivity.this,
                                BusinessUtil.getErrorInfoByException(OrderPayActivity.this, (Exception) throwable));
                    }
                });
        RxSubscriptions.add(mAliPayRx);
    }

    /**
     * 监听支付宝webpay支付结果
     */
    private void setAliWebPayResultCallback() {
        mAliWebPayRx = RxBus.getDefault().toObserverable(AliPayUtil.ALIWEB_PAY_SUCCESS, String.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        //保存默认支付名称
                        PreferencesUtls.getInstance(OrderPayActivity.this).putString(DEFAULT_PAY_CHANNEL_KEY, tv_payWay.getText().toString());
                        log.d("setAliWebPayResultCallback == " + s);
                        queryOrderStatus();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        dismisLoading();
                        ErrorCodeUtil.ShowErrorSompMsg(
                                OrderPayActivity.this,
                                BusinessUtil.getErrorInfoByException(OrderPayActivity.this, (Exception) throwable));
                    }
                });
        RxSubscriptions.add(mAliWebPayRx);
    }
    /************************* 支付宝支付分割线：look up***********************/

    /**
     * 查询订单支付情况（NOTE：在支付操作成功后需要查询订单状态确认套餐订单是否支付成功）
     */
    private void queryOrderStatus() {
        showLoading();
        WXPayUtil.resetWXPayRespCode();
        getOrderInfoPresenter().queryOrderStatus(orderInfo.getOrderId());
    }

    /**
     * 显示 切换支付方式窗口
     */
    private void showSwitchTypeDialog() {
        if (payTypeLayout == null) {
            payTypeLayout = new PayTypeLayout(this, paychannels);
            payTypeLayout.setPayTypeItemSelectListener(new PayTypeLayout.OnSelectPayTypeItemOnClickListener() {
                public void onSelectItem(PayTypeEnum payTypeEnum) {
                    OrderPayActivity.this.payTypeEnum = payTypeEnum;
                    tv_payWay.setText(payTypeLayout.getPayType(payTypeEnum));
                }
            });
        }
        payTypeLayout.show();
    }

    public void showLoading() {
        if (mDialog == null) {
            mDialog = new ProgressDialog(this);
            mDialog.setTitle(getString(R.string.sendingRequest));
            mDialog.setMessage(getString(R.string.waiting));
            mDialog.setCanceledOnTouchOutside(false);
        }
        mDialog.show();
    }

    private void dismisLoading() {
        if (mDialog != null && mDialog.isShowing())
            mDialog.dismiss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxSubscriptions.remove(mAliWebPayRx);
        RxSubscriptions.remove(mAliPayRx);
        RxSubscriptions.remove(mWxPayRx);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (PackageType.CORE == packageType) {
            BusinessUtil.sendReportByClickType(this, FunctionNameFindId.OnstarPackage_purahcecancel.getStringValue());
        } else if (PackageType.DATA == packageType) {
            BusinessUtil.sendReportByClickType(this, FunctionNameFindId.F4Gpacakge_purchasecancel.getStringValue());
        }
    }

    /**
     * 获取支付渠道数据
     */
    private void getPayChannelData() {
        presenter = new PayChannelPresenter((OrderPayActivity.this.getScheduler()));
        presenter.setView(this);
        presenter.getPayChannelData();
    }

    @Override
    public void setLoading(boolean isLoading) {

    }

    @Override
    public void onResponseError(OnStarException e) {
        Log.e("onResponseError", "");
    }

    @Override
    public void onReponseSuccess(Object object) {
        //获取支付渠道
        List<PayChannelResponseEntity.ChannelsBean> channels = ((PayChannelResponseEntity) object).getChannels();
        paychannels = channels;
        for (int i = 0; i < channels.size(); i++) {
            if (channels.get(i).getIsDefault().equals("1")) {
                //获取默认支付名称
                String defaultPay = PreferencesUtls.getInstance(OrderPayActivity.this).getString(DEFAULT_PAY_CHANNEL_KEY, "");
                //设置默认渠道名称
                if (!TextUtils.isEmpty(defaultPay)) {
                    tv_payWay.setText(defaultPay);
                } else {
                    tv_payWay.setText(channels.get(i).getDescription());
                }
                break;
            }
        }
    }

    @Override
    public Activity onActivity() {
        return this;
    }
}